package com.dailyblue.project.smbms.order.controller;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.spring.project.smbms.commons.bean.Orders;
import com.dailyblue.java.spring.project.smbms.commons.bean.Orders2;
import com.dailyblue.java.spring.project.smbms.commons.config.JsonResult;
import com.dailyblue.java.spring.project.smbms.commons.config.ResultTool;
import com.dailyblue.java.spring.project.smbms.commons.service.OrdersService;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrdersService ordersService;

    @GetMapping("/place")
    public JsonResult<String> placeAnOrder(Orders order, String address, String phone) throws Exception {
        ordersService.save(order);
        sendMsg(address, phone, order);
        return ResultTool.success();
    }

    private void sendMsg(String address, String phone, Orders order) throws Exception {
        Orders2 o = new Orders2();
        o.setAddress(address);
        o.setPhone(phone);
        o.setBid(order.getBid());
        o.setNum(order.getNum());
        String json = JSONArray.toJSONString(o);
        Message message = new Message();
        message.setTopic("ORDER");
        message.setTags("TagA");
        message.setBody(json.getBytes(StandardCharsets.UTF_8));
        DefaultMQProducer producer = new DefaultMQProducer("group_a");
        producer.setNamesrvAddr("10.211.55.4:9876");
        producer.start();
        SendResult result = producer.send(message);
        System.out.println(result);
        producer.shutdown();
    }
}
